package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.myapplication.adapter.ClassmateAdapter;
import com.example.myapplication.polo.Classmate;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    ListView lv_classmate;
    List<Classmate> classmateList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        network();
    }

    private void network() {
        String url="http://10.2.64.50:8080/app3/classmate/list";
        RequestQueue requestQueue= Volley.newRequestQueue(MainActivity.this);
        JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, url, (JSONObject) null,  new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    JSONArray list= jsonObject.getJSONArray("list");

                    Gson gson=new Gson();
                    classmateList= gson.fromJson(list.toString(),new TypeToken<List<Classmate>>(){



                    }.getType());
                    ClassmateAdapter adapter = new ClassmateAdapter(MainActivity.this,classmateList);
                    lv_classmate.setAdapter(adapter);


                }catch (JSONException e){
                    e.printStackTrace();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("响应失败");
            }
        });
        requestQueue.add(jsonObjectRequest);
    }



    private void init() {
        lv_classmate=(ListView)findViewById(R.id.lv_classmate);
    }


}